package com.heima.wemedia.controller.v1;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.wemedia.IWeMediaClient;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.service.NewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Objects;

/**
 * @author Ronaldo
 * @date 2021/8/1
 */
@RestController
@RequestMapping("/api/v1")
@Slf4j
public class WmUserController implements IWeMediaClient {

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private NewsService newsService;

    /**
     * 创建自媒体用户
     * @param wmUser
     * @return
     */
    @Override
    @PostMapping("/user/save")
    public ResponseResult save(@RequestBody WmUser wmUser) {
        log.info("insert wmUser {}" + wmUser);

        if (Objects.isNull(wmUser)){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmUserService.save(wmUser);
        return ResponseResult.okResult("ok");
    }

    @Override
    /**
     * 根据用户名查询自媒体用户
     * @param name
     * @return
     */
    @GetMapping("/user/findByName/{name}")
    public WmUser findByName(@PathVariable("name") String name){
        log.info("select wmUser by name {}" + name);

        if (StringUtils.isBlank(name)){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }
        return wmUserService.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,name));
    }

    @Override
    @GetMapping("/news/findOne/{id}")
    public WmNews findNewsById(@PathVariable("id") Integer id) {
        log.info("find news by id{}",id);
        if (Objects.isNull(id)){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }
        return newsService.getById(id);
    }

    @Override
    @PostMapping("/news/update")
    public ResponseResult updateNews(@RequestBody WmNews news) {
        log.info("update WmNews by news{}",news);
        if (Objects.isNull(news)){
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }
        newsService.updateById(news);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    @GetMapping("/news/findRelease")
    public List<Integer> findReleaseNewsId() {
        return newsService.findReleaseNewsId();
    }
}
